package com.customization.api.e9sso.cmd;

import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.workflow.biz.freeNode.FreeNodeBiz;
import com.engine.workflow.biz.publicApi.RequestOperateBiz;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.resource.ResourceComInfo;
import weaver.workflow.webservices.WorkflowRequestTableField;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;


public class SubmitCmd extends AbstractCommonCommand<Map<String,Object>> {

    private HttpServletRequest request=null;
    public SubmitCmd(User user, HttpServletRequest request) {
        this.user = user;
        this.params = ParamUtil.request2Map(request);
        this.request=request;

        Enumeration<String> er = request.getParameterNames();
        while (er.hasMoreElements()) {
            String name = (String) er.nextElement();
            String value = request.getParameter(name);
            this.params.put(name, value);
        }
        Console.log(this.params.toString());

    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        String uuid=UUID.randomUUID().toString();
        Console.log(uuid+"输入参数params:"+params.toString());
        Map<String, Object> apidatas = new HashMap<String, Object>();
        apidatas.put("status",true);
        apidatas.put("msg","提交成功!");

        RecordSet rs=new RecordSet();

        String approverWorkcode=Util.null2String(params.get("approverWorkcode"));
        String requestId=Util.null2String(params.get("requestId"));



        RecordSet rst= new RecordSet();
        String  sql=" update  uf_DispatchSSF set  approver_workcode='"+approverWorkcode+"' where request_id='"+requestId+"'";
        Console.log("sql:"+sql);
        rst.execute(sql);

        WorkflowRequestOperatePA workflowRequestOperatePA = new WorkflowRequestOperatePAImpl();;
        //2021/3/10 12:21 lth    增加签字意见里面显示支付出纳名称;
        ReqOperateRequestEntity request2Entity=RequestOperateBiz.request2Entity(this.request);

        /*
        if(!approverWorkcode.equals("")) {
            request2Entity.setRemark(request2Entity.getRemark() + "</br></br>流程已经到达支付环节，如有疑问请联系 <a href='/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/3627' target='_blank'>邹华俊</a>");
        }
        */
        //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  Start
        String sqls=" select  CURRENTNODEID,WORKFLOWID from  workflow_requestbase where requestid='"+requestId+"'";
        rst.execute(sqls);
        String currentNodeId="";
        String workflowId="";
        Console.log("查询当前节点:"+sqls);
        if(rst.next()){
            currentNodeId=rst.getString("CURRENTNODEID");
            workflowId=rst.getString("WORKFLOWID");
        }
        //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  end

        PAResponseEntity paResponseEntity = workflowRequestOperatePA.submitRequest(this.user,request2Entity);
        JSONObject  result=JSONObject.parseObject(JSONObject.toJSONString(paResponseEntity));
         String code= Util.null2String(result.get("code"));
         if(!code.equals("SUCCESS")){
             apidatas.put("status",false);
             apidatas.put("msg","提交失败!");
             apidatas.put("errMsg",Util.null2String(result.get("errMsg")));
             apidatas.put("code",code);
             Console.log(uuid+"返回值:"+apidatas.toString());
             return apidatas;
         }else{

             //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  Start
             String nextPayNode=","+Util.null2String(rst.getPropValue("angel_fna", "nextPayNode_NodeIds"))+",";

             /*
             Console.log("nextPayNode:"+nextPayNode);
             Console.log("currentNodeId:"+currentNodeId);
             Console.log("nextPayNode.contains(\",\"+currentNodeId+\",\"):"+nextPayNode.contains(","+currentNodeId+","));
             Console.log("!currentNodeId.equals(\"\")&&!nextPayNode.equals(\",,\")&&nextPayNode.contains(\",\"+currentNodeId+\",\"):"+(!currentNodeId.equals("")&&!nextPayNode.equals(",,")&&nextPayNode.contains(","+currentNodeId+",")));
              */


             if(!currentNodeId.equals("")&&!nextPayNode.equals(",,")&&nextPayNode.contains(","+currentNodeId+",")){
                 sqls=" select  logid,REMARK,nodeid,logtype from  WORKFLOW_REQUESTLOG  where    (logtype='0'  or logtype='2')  and nodeid='"+currentNodeId+"' and  requestid='"+requestId+"' order by   logid  desc ";
                 Console.log("查询当前节点的签字意见:"+sqls);
                 rst.execute(sqls);
                 String logid="";
                 if(rst.next()){
                     logid=rst.getString("logid");
                 }
                 if(!"".equals(logid)) {



                     sqls="select formid from  workflow_base where id='"+workflowId+"'";
                     Console.log("formid:"+sqls);
                     rst.execute(sqls);
                     rst.first();
                     int formid=rst.getInt("formid");


                     sqls="select * from  formtable_main_"+Math.abs(formid)+" where requestid='"+requestId+"'";
                     Console.log("gsdm:"+sqls);
                     rst.execute(sqls);
                     rst.first();

                     String gsdm=Util.null2String(rst.getString("gsdm5"));
                     if(gsdm.equals("")){
                         gsdm=Util.null2String(rst.getString("gsdm2"));
                     }else{
                         gsdm=Util.null2String(rst.getString("gsdm"));
                     }

                     sqls=" select gsdm,cn from uf_companyTreasurer where gsdm='"+gsdm+"'";
                     Console.log("resourceid:"+sqls);
                     rst.execute(sqls);
                     boolean isUpdate=false;
                     String cn="3627";
                     String lastname="邹华俊";
                     if(rst.next()){
                         cn=rst.getString("cn");
                         try {
                             ResourceComInfo rci=new ResourceComInfo();
                             lastname=rci.getLastname(cn);
                         } catch (Exception e) {
                             e.printStackTrace();
                         }
                         isUpdate=true;
                     }

                     sqls = " update  WORKFLOW_REQUESTLOG  set REMARK=REMARK||'</br></br>流程已经到达支付环节，如有疑问请联系 <a href=''/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/"+cn+"'' target=''_blank''>"+lastname+"</a>。</br></br>' where logid='"+logid+"'   and nodeid='" + currentNodeId + "' and  requestid='" + requestId + "'";
                     Console.log("updateSql:"+sqls);
                     if(isUpdate) {
                         rst.execute(sqls);
                     }

                     Console.log(isUpdate+"更新当前签字意见:" + sqls);


                 }
             }else{
                 Console.log("不在支付节点审核环节");
             }
             //2021/3/12 09:28 lth    添加支付节点显示会计名称的需求  End


         }

        Console.log(uuid+"返回值:"+apidatas.toString());
        return apidatas;
    }



    private boolean pushStatusYx(int typeid,String title, String context, String linkUrl, String linkMobileUrl, Set<String> userIdList,int creator) {
        MessageType messageType = MessageType.newInstance(typeid); // 消息来源（见文档第四点补充）
        try {
            MessageBean messageBean = Util_Message.createMessage(messageType, userIdList, title, context, linkUrl,
                    linkMobileUrl);
            messageBean.setCreater(creator);// 创建人id
            return Util_Message.store(messageBean);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }


    public static String getCreateNodeID(String requestid){
        RecordSet rs= new RecordSet();
        if(requestid.equals("")){
            return "";
        }
        rs.execute("select nodeid from  workflow_nodebase,workflow_flownode,workflow_requestbase where workflow_flownode.nodeid=workflow_nodebase.id and nodetype=0 and workflow_requestbase.workflowid=workflow_flownode.workflowid and workflow_requestbase.requestid='"+requestid+"'");
        rs.first();

        return rs.getString("nodeid");
    }
    public static String getAcquiringNodeID(String requestid){
        RecordSet rs= new RecordSet();
        if(requestid.equals("")){
            return "";
        }
        rs.execute("select nodeid from  workflow_nodebase,workflow_flownode,workflow_requestbase where workflow_flownode.nodeid=workflow_nodebase.id   and  workflow_requestbase.workflowid=workflow_flownode.workflowid and workflow_requestbase.requestid='"+requestid+"' and  workflow_nodebase.NODENAME like '%收单%'");
        rs.first();
        return rs.getString("nodeid");
    }




    public ReqOperateRequestEntity request2Entity() {
        ReqOperateRequestEntity var1 = new ReqOperateRequestEntity();

        try {
            int var2 = Util.getIntValue(Util.null2String(this.params.get("workflowId")));
            int var3 = Util.getIntValue(Util.null2String(this.params.get("requestId")));
            String var4 = Util.null2String(this.params.get("requestName"));
            int var5 = Util.getIntValue(Util.null2String(this.params.get("userId")));
            int var6 = Util.getIntValue(Util.null2String(this.params.get("forwardFlag")));
            String var7 = Util.null2String(this.params.get("forwardResourceIds"));
            String var8 = Util.null2String(this.params.get("mainData"));
            if (!"".equals(var8)) {
                try {
                    List var9 = JSONObject.parseArray(var8, WorkflowRequestTableField.class);
                    var1.setMainData(var9);
                } catch (Exception var16) {
                    var16.printStackTrace();
                }
            }

            String var18 = Util.null2String(this.params.get("detailData"));
            if (!"".equals(var18)) {
                try {
               //     List var10 = JSONObject.parseArray(var18, WorkflowDetailTableInfoEntity.class);
                 //   var1.setDetailData(var10);
                } catch (Exception var15) {
                    var15.printStackTrace();
                }
            }

            String var19 = Util.null2String(this.params.get("remark"));
            String var11 = Util.null2String(this.params.get("requestLevel"));
            String var12 = Util.null2String(this.params.get("otherParams"));
            if (!"".equals(var12)) {
                try {
                    Map var13 = (Map)JSONObject.parseObject(var12, Map.class);
                    var1.setOtherParams(var13);
                } catch (Exception var14) {
                    var14.printStackTrace();
                }
            }
            Console.log("OtherParams:"+var1.getOtherParams().toString());

            var1.setWorkflowId(var2);
            var1.setRequestId(var3);
            var1.setRequestName(var4);
            var1.setUserId(var5);
            var1.setRemark(var19);
            var1.setRequestLevel(var11);
            var1.setForwardFlag(var6);
            var1.setForwardResourceIds(var7);
            var1.setClientIp(Util.null2String(this.params.get("param_ip")));
            int var20 = Util.getIntValue(Util.null2String(this.params.get("submitNodeId")));
            if (var20 > 0 || FreeNodeBiz.isFreeNode(var20)) {
                var1.setSubmitNodeId(var20);
                var1.setEnableIntervenor("1".equals(Util.null2s(Util.null2String(this.params.get("enableIntervenor")), "1")));
                var1.setSignType(Util.getIntValue(Util.null2String(this.params.get("SignType")), 0));
                var1.setIntervenorid(Util.null2String(this.params.get("Intervenorid")));
            }
        } catch (Exception var17) {
            var17.printStackTrace();

        }

        return var1;
    }
}
